<?php
	class DataController extends Sss_Controller_Default
	{
		public function postDataAction()
		{
			$this->_helper->getHelper('layout')->disableLayout();
			// Get params
			$params = $this->_request->getParams();
			$message = "";
			$postDataTable = new Shepherd_Model_Mapper_PostData();
			$hardwareTable = new Application_Model_Mapper_Hardware();
			$systemTypeTable   = new Application_Model_Mapper_SystemType();
			$hardwareValueTypeTable   = new Application_Model_Mapper_HardwareValueType();
			$instanceTable = new Application_Model_Mapper_Instance();
			$siteName = $params['site_name'];
			$duplicate_handling = $params['duplicate_handling'];
			$siteUrl = ''; 
			try{
				foreach ($_POST as $key => $value) {
					$siteUrl .= "$key=$value&";
				} 
				if($siteUrl != ''){
					$siteUrl = substr($siteUrl, 0 , strlen($siteUrl)-1);
				} 
			}catch(Exception $e){
				continue;
			}
			Sss_Ultility_Common::loggerPostData()->log(date("m-d-Y H:i:j")."\n ".DOMAIN_SYSTEM.'/data/post-data?'.$siteUrl, Zend_Log::INFO); 
			try{
				$handle = $instanceTable->getInstanceByHandle($siteName);
				Sss_Ultility_Common::checkCreateColumn($handle->instanceid);
				$arrNoExistedHardware = array();
				$arrDuplicateData = array();
				$arrValues = array();
				$arrayPoses = array();
				if ($handle && !$handle->isarchived) {
					$postDataTable->_setTableName($handle->instanceid);
					foreach ($params as $key=>$p) {
						if (strpos($key, 'value') === 0) {
							$arrValues[] = $p;
						}

						if (strpos($key, 'pos') === 0) {
							$arrayPoses[] = $p;
						}
					}

					$isPostSuccess = false;
					if (count($arrValues) > 0) {
						foreach($arrValues as $v){
							$arr = explode('_', $v);
							$arrPostData = Sss_Ultility_Common::getColumnInPostData($v, null , null,  $handle->instanceid);
							// Check cols exist and if not exist when insert cols to table
							$postDataTable->checkEsixtedColumns($arrPostData['cols'], $handle->instanceid);
							$hardware = $hardwareTable->checkExistBySerialNumber($arr[3], $siteName);
							//Add auto hardware if serialID not exists
							if($hardware == false) { 
								Sss_Ultility_Common::autoAddHardware($arr[3],$handle->stocklocationname,$handle->stocklocation);
								$hardware = $hardwareTable->checkExistBySerialNumber($arr[3], $siteName);
							}
							//End add
							// When hardware exist to application
							if($hardware){ 
								$isPostSuccess = true;
								$hardwareId = $hardware->hardwareid;
								if(!is_numeric($arr[1])){
									$createdDate = Sss_Ultility_Common::getDateTimeNumber($arr[1]);
								}else{
									$createdDate = $arr[1];
								}
								
								// Check insert or update data
								$duplicatedData =  $postDataTable->checkDuplicateData($siteName, $arr[1], $hardwareId, $arrPostData['cols'], $arr[2],  $handle->instanceid);
								$existedData = $postDataTable->checkDataExist($siteName, $arr[1], $hardwareId, $handle->instanceid);
								$paramValues['hardwareid']  = $hardwareId;
								$paramValues['createddate'] = $createdDate;
								$paramValues['sitename']    = $siteName;
								$paramValues['instanceid']  = $handle->instanceid;
								$paramValues['v']           = $v;
								$paramValues['existeddata'] = $existedData;
								$paramValues['postdata']    = $arrPostData['postdata'];
								switch($duplicate_handling) {
									case 'exception':
									case '':
										if ($duplicatedData) {
											$arrDuplicateData[] = $v;
										} else {
											if ($existedData) {
												$dataId = Sss_Ultility_Common::processSavePostData(true, $paramValues);
												//Sss_Ultility_Common::loggerPostData()->log(date("m-d-Y H:i:j").'---'.$site_name.'---'.$hardwareId.'---'.$arr[1], Zend_Log::INFO); 
											} else {
												$dataId = Sss_Ultility_Common::processSavePostData(false, $paramValues); 
												//Sss_Ultility_Common::loggerPostData()->log(date("m-d-Y H:i:j").'---'.$site_name.'---'.$hardwareId.'---'.$arr[1], Zend_Log::INFO); 
											}
										}
										break;
									case 'ignore':
										// ignore new value
										if (!$duplicatedData) {
											if ($existedData) {
												$dataId = Sss_Ultility_Common::processSavePostData(true, $paramValues); 
												//Sss_Ultility_Common::loggerPostData()->log(date("m-d-Y H:i:j").'---'.$site_name.'---'.$hardwareId.'---'.$arr[1], Zend_Log::INFO); 
											} else {
												$dataId = Sss_Ultility_Common::processSavePostData(false, $paramValues); 
												//Sss_Ultility_Common::loggerPostData()->log(date("m-d-Y H:i:j").'---'.$site_name.'---'.$hardwareId.'---'.$arr[1], Zend_Log::INFO); 
											}
										}
										break;
									case 'override':
										if ($existedData || $duplicatedData) {
											$dataId = Sss_Ultility_Common::processSavePostData(true, $paramValues); 
											//Sss_Ultility_Common::loggerPostData()->log(date("m-d-Y H:i:j").'---'.$site_name.'---'.$hardwareId.'---'.$arr[1], Zend_Log::INFO); 
										} else {
											$dataId = Sss_Ultility_Common::processSavePostData(false, $paramValues);
											//Sss_Ultility_Common::loggerPostData()->log(date("m-d-Y H:i:j").'---'.$site_name.'---'.$hardwareId.'---'.$arr[1], Zend_Log::INFO); 
										}
										break;
								};

								$systemType = $systemTypeTable->getSystemByTypeCode($arrPostData['cols']);
								// Check system type exist
								if($systemType){
									$systemtypeId = $systemType->systemtypeid;
									$hardwareValueType = $hardwareValueTypeTable->getHardwareValueTypeExist($hardwareId, $systemtypeId, 1);
									// Check hardware value type not exist in database and if not exist will insert hardware value type to database
									if(!$hardwareValueType){
										$hardwareValueTypeNew = new Application_Model_HardwareValueType();
										$hardwareValueTypeNew->setHardware($hardwareId);
										$hardwareValueTypeNew->setSystemType($systemtypeId);
										$hardwareValueTypeNew->setIsused(1);
										$hardwareId = $hardwareValueTypeTable->save($hardwareValueTypeNew);
									}
								}
							} else {
								$arrNoExistedHardware[] = $arr[3];
								//Sss_Ultility_Common::loggerPostData()->log(date("m-d-Y H:i:j").'---'.$site_name.'---'.$arr[3].'---'.$arr[4].'---'.$arr[1], Zend_Log::ALERT); 												
							}
						}	
					}

					if (count($arrayPoses) > 0) {
						foreach ($arrayPoses as $v) {
							$arr = explode('_', $v);
							$hardware = $hardwareTable->checkExistBySerialNumber($arr[1], $siteName);
							if($hardware) {
								if(!is_numeric($arr[2])){
									$createdDate = Sss_Ultility_Common::getDateTimeNumber($arr[2]);
								}else{
									$createdDate   = $arr[2];
								} 
								$isPostSuccess = true;
								$hardwareId = $hardware->hardwareid;
								// Check insert or update data
								$arrayValue = array (
								'created_date' => $arr[2],
								'hardware' => $hardwareId,
								'pos_type' => $arr[3],
								'lat_value' => $arr[4],
								'long_value' => $arr[5],
								'error' => $arr[6],
								'speed' => $arr[7],
								'heading' => $arr[8],
								);
								$paramValues['hardwareid']  = $hardwareId;
								$paramValues['createddate'] = $createdDate;
								$paramValues['sitename']    = $siteName;
								$paramValues['instanceid']  = $handle->instanceid;
								$duplicatedData =  $postDataTable->checkDuplicatePosData($siteName, $arrayValue, $handle->instanceid);
								$existedData = $postDataTable->checkDataExist($siteName, $arr[1], $hardwareId, $handle->instanceid);
								
								switch($duplicate_handling) {
									case 'exception':
									case '':
										if ($duplicatedData) {
											$arrDuplicateData[] = $v;
										} else {
											if ($existedData) {
												$dataId = Sss_Ultility_Common::processSavePostData(true, $paramValues, false, $arr);
												//Sss_Ultility_Common::loggerPostData()->log(date("m-d-Y H:i:j").'---'.$site_name.'---'.$hardwareId.'---'.$arr[3].'---'.$arr[4], Zend_Log::INFO); 
											} else {
												$dataId = Sss_Ultility_Common::processSavePostData(false, $paramValues, false, $arr);
												//Sss_Ultility_Common::loggerPostData()->log(date("m-d-Y H:i:j").'---'.$site_name.'---'.$hardwareId.'---'.$arr[3].'---'.$arr[4], Zend_Log::INFO); 
											}
										}
										break;
									case 'ignore':
										break;
									case 'override':
										if ($existedData || $duplicatedData) {
											$dataId = Sss_Ultility_Common::processSavePostData(true, $paramValues, false, $arr);
										} else {
											$dataId = Sss_Ultility_Common::processSavePostData(false, $paramValues, false, $arr);
										}
										break;
								};
							} else {
								$arrNoExistedHardware[] = $arr[1];
							}
						}	
					}

				} else {
					$message = sprintf(Resources::_('WRONG_INSTANCE'), $site_name);
				}				
			}catch(Exception $e){
				Sss_Ultility_Common::loggerPostData()->log($e, Zend_Log::ERR);
				$this->view->assign("msgpostdata", Resources::_('CAN_NOT_POST_DATA'));
				return;
			}

			if (count($arrNoExistedHardware) > 0) {  
				$message .= sprintf(Resources::_('POST_DATA_NOT_EXISTED_HARDWARE'), $site_name);
				$message .= implode("<br />", $arrNoExistedHardware);	
			}
			if (count($arrDuplicateData) > 0) {
				$message .= Resources::_('POST_DATA_DUPLICATED_HARDWARE');
				$message .= implode("<br />", $arrDuplicateData);	
			}
			if ($message == "") {

				$this->view->flag = 1;
				$message = Resources::_('CAN_POST_DATA'); 
			}

			$this->view->assign("msgpostdata", $message); 
			if($message == Resources::_('CAN_POST_DATA')) {
				$message = "\n OK \n ".$message." \n ".Resources::_('NOTE_MESSAGE')."\n ================================================================================================================" ;
				Sss_Ultility_Common::loggerPostData()->log(date("m-d-Y H:i:j").$message, Zend_Log::INFO);
			}else{
				$message = "\n NOK \n ".$message." \n ".Resources::_('NOTE_MESSAGE')."\n ================================================================================================================" ;
				Sss_Ultility_Common::loggerPostData()->log(date("m-d-Y H:i:j").$message, Zend_Log::INFO); 
			}

		}
	}